using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;
using System;
using System.Collections.Generic;
using System.Collections;

namespace MyFrame.Load
{
    public class SceneLoader : MonoBehaviour
    {
        public static event Action LoadingStarted;
        public static event Action<float> LoadingProgress;
        public static event Action LoadingSuccessed;
        public static event Action LoadingCompleted;

        static SceneInstance loadedSceneInstance;

        public static bool ShowLoadingScreen { get; private set; }
        public static bool IsSceneLoaded { get; private set; }


        static IEnumerator LoadSceneAsync(object sceneName, bool showLoadingScreen, bool loadScneneSingle = true, bool activateOnLoad = true)
        {
            LoadSceneMode LoadSceneMode = loadScneneSingle ? LoadSceneMode.Single : LoadSceneMode.Additive;
            AsyncOperationHandle<SceneInstance> handle = Addressables.LoadSceneAsync(sceneName, LoadSceneMode, activateOnLoad);

            LoadingStarted?.Invoke();
            ShowLoadingScreen = showLoadingScreen;
            while (handle.Status != AsyncOperationStatus.Succeeded)
            {
                LoadingProgress?.Invoke(handle.PercentComplete);
                yield return null;
            }

            if (activateOnLoad)
            {
                LoadingCompleted?.Invoke();
                yield break;
            }

            LoadingSuccessed?.Invoke();
            IsSceneLoaded = true;

            loadedSceneInstance = handle.Result;
        }
        /// <summary>
        /// 手动激活加载好的场景
        /// </summary>
        public static void ActivatelLoadedScene()
        {
            loadedSceneInstance.ActivateAsync().completed += (obj) =>
            {
                IsSceneLoaded = false;
                loadedSceneInstance = default;
                LoadingCompleted?.Invoke();
            };
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sceneName"></param>
        /// <param name="showLoadingScreen">是否显示加载中场景</param>
        /// <param name="loadScneneSingle"></param>
        /// <param name="activateOnLoad">是否立刻激活</param>
        /// <returns></returns>
        public void LoadScene(object sceneName, bool showLoadingScreen = false, bool loadScneneSingle = true, bool activateOnLoad = true)
        {
            StartCoroutine(LoadSceneAsync(sceneName, showLoadingScreen, loadScneneSingle, activateOnLoad));
        }
    }
}